package com.bnyy.medicalHousekeeper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.SizeUtils;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.gbp.GlideUtils.CircleTransform;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.bumptech.glide.request.transition.Transition;

import java.security.MessageDigest;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class GlideHelper {

    private static final String TAG = "GlideHelper";
    private static int DEFAULT_IMAGE = R.mipmap.default_1_1, PLACE_HOLDER = R.mipmap.default_1_1;

    public static void init(int defaultImage, int placeHolder) {
        DEFAULT_IMAGE = R.mipmap.default_1_1;
        PLACE_HOLDER = R.mipmap.default_1_1;
    }

    /**
     * Function:Glide Transformation 实现圆角图片
     */
    public static class GlideRoundTransform extends BitmapTransformation {

        private float radius = 0f;

        public GlideRoundTransform() {
            this(4);
        }

        public GlideRoundTransform(int dp) {
            super();
//            this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
            this.radius = dp;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return roundCrop(pool, toTransform);
        }

        private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
            return result;
        }

        @Override
        public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

        }
    }

    public static GlideUrl getGlideUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        LazyHeaders.Builder builder = new LazyHeaders.Builder();
        if (!TextUtils.isEmpty(RequestManager.getmCokkie())) {
            builder.setHeader("Cookie", RequestManager.getmCokkie());
            return new GlideUrl(url, builder.build());
        }
        return new GlideUrl(url);
    }

    public static void setCircleImage(Context context, String s, ImageView iv) {
        setCircleImage(context, s, iv, 0);
    }

    public static void setCircleImage(Context context, String s, ImageView iv, int defaultImage) {
        setCircleImage(context, s, iv, 0, Color.WHITE, defaultImage);
    }

    public static void setCircleImage(Context context, String s, ImageView iv, int borderWidth, int borderColor) {
        setCircleImage(context, s, iv, borderWidth, borderColor, 0);
    }

    public static void setCircleImage(Context context, String s, ImageView iv, int borderWidth, int borderColor, int defaultImage) {
        RequestBuilder<Drawable> builder = Glide.with(context)
                .load(s)
                .apply(new RequestOptions().transform(new CircleTransform(borderWidth, borderColor)));

        setImage(builder, iv, defaultImage);
    }

    public static void setCircleImage(Context context, int imgResId, ImageView iv) {
        RequestBuilder<Drawable> builder = Glide.with(context)
                .load(imgResId)
                .apply(new RequestOptions().transform(new CircleTransform(0, Color.WHITE)));

        setImage(builder, iv);
    }

    public static void setHeader(Context context, String s, ImageView iv) {
        setCircleImage(context, s, iv, R.mipmap.icon_default_header_man);
    }

    private void setImage(Context context, String url, ImageView iv, int defaultImage, BitmapTransformation... bitmapTransformations) {
        RequestBuilder<Drawable> builder = Glide.with(context)
                .load(url)
                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(bitmapTransformations)));

        if (defaultImage == 0) {
            if (DEFAULT_IMAGE != 0) {
                builder = builder.error(DEFAULT_IMAGE);
            }
            if (PLACE_HOLDER != 0) {
                builder = builder.error(PLACE_HOLDER);
            }
        } else {
            builder = builder.error(defaultImage).placeholder(defaultImage);
        }

        builder.addListener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        }).into(iv);
    }

    private void setImage(Context context, String url, CustomTarget<Drawable> customTarget, int defaultImage, BitmapTransformation... bitmapTransformations) {
        RequestBuilder<Drawable> builder = Glide.with(context)
                .load(url)
                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(bitmapTransformations)));

        if (defaultImage == 0) {
            if (DEFAULT_IMAGE != 0) {
                builder = builder.error(DEFAULT_IMAGE);
            }
            if (PLACE_HOLDER != 0) {
                builder = builder.error(PLACE_HOLDER);
            }
        } else {
            builder = builder.error(defaultImage).placeholder(defaultImage);
        }

        builder.into(new CustomTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                customTarget.onResourceReady(resource, transition);
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
                customTarget.onLoadCleared(placeholder);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                customTarget.onLoadFailed(errorDrawable);
            }
        });
    }

    public static void setRoundImage(Context context, int s, ImageView iv) {
        setRoundImage(context, s, iv, SizeUtils.dp2px(10));
    }

    public static void setRoundImage(Context context, int imgResId, ImageView iv, int radius) {
        RequestBuilder<Drawable> builder = Glide.with(context)
                .load(imgResId)
                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(
                        new CenterCrop(),
                        new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL))));
        setImage(builder, iv);
    }

    public static void setRoundImage(Context context, String s, ImageView iv) {
        setRoundImage(context, s, iv, SizeUtils.dp2px(10));
    }

    public static void setRoundImage(Context context, String s, ImageView iv, int radius) {
        RequestBuilder<Drawable> builder = Glide.with(context)
                .load(GlideHelper.getGlideUrl(s))
                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(
                        new CenterCrop(),
                        new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL))));
        setImage(builder, iv);
    }

    public static void setImage(Context context, String s, ImageView iv) {
        setImage(Glide.with(context).load(getGlideUrl(s)), iv);
    }

    public static void setImage(Context context, int imgResId, ImageView iv) {
        setImage(Glide.with(context).load(imgResId), iv);
    }

    public static void setImage(RequestBuilder<Drawable> builder, ImageView iv) {
        setImage(builder, iv, 0);
    }

    public static void setImage(RequestBuilder<Drawable> builder, ImageView iv, int defaultImage) {
        if (defaultImage == 0) {
            if (DEFAULT_IMAGE != 0) {
                builder = builder.error(DEFAULT_IMAGE);
            }
            if (PLACE_HOLDER != 0) {
                builder = builder.error(PLACE_HOLDER);
            }
        } else {
            builder = builder.error(defaultImage).placeholder(defaultImage);
        }
        builder.transition(DrawableTransitionOptions.with(new DrawableCrossFadeFactory.Builder(300).setCrossFadeEnabled(true).build()))
                .addListener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                }).into(iv);
    }
}




























